import re
def replace_block(file_path, original_block_head, new_block_content):
	with open(file_path, 'r', encoding='utf-8') as file:
		file_data = file.read()

	# block_start = original_block_head

	# regex_pattern = r'({}.*?})'.format(re.escape(original_block_head))
	regex_pattern ='(' + original_block_head + ' = \\{.*?\\})'

	# Use regex_pattern to replace
	updated_data = re.sub(regex_pattern, new_block_content, file_data, flags=re.DOTALL)
		# updated_data = re.sub(r'(diff_normal_player = \{.*?\})', new_block_content, file_data, flags=re.DOTALL)

	with open(file_path, 'w', encoding='utf-8') as file:
		file.write(updated_data)

	print("All blocks is replaced!")

def replace_block_no_reg(file_path, original_block_head, new_block_content):
	# 临时文件路径，用于存储处理后的内容
	lines_to_keep = []
	# 标记是否开始删除块内容
	start_check = False
	insert_index = None
	ignore_in_block = False
	nest = 0
	stop_check = False
	# 读取原文件并写入临时文件，跳过需要删除的块
	with open(file_path, 'r', encoding='utf-8') as read_file:
		for idx, line in enumerate(read_file):
			# 检查是否开始新的块，如果是则开始忽略内容
			if not start_check and line.strip() == original_block_head + " = {":
				start_check = True
				insert_index = idx  # 记录起始行位置
				continue  # 跳过当前行不写入
			# 如果不在删除范围内，则写入该行
			if not start_check:
				lines_to_keep.append(line)
			# 当前行以'}'开始，表示结束标记，重置flag并继续处理下一行
			if '{' in line and start_check:
				nest += 1
			if '}' in line and start_check:
				nest -= 1
			if nest < 0:
				start_check = False
				continue
			
	# print(lines_to_keep)
	if insert_index is not None:		
		lines_to_keep[insert_index:insert_index] = [new_block_content + "\n"]  # 插入新块并保持格式

	with open(file_path, 'w', encoding='utf-8') as write_file:
		write_file.writelines(lines_to_keep)